<template>
  <div>
    <el-upload :disabled="disabledUpload" :data="fileListMain" :file-list="fileList" :limit="props.maxLimit" action="#" list-type="picture-card" :auto-upload="false" :class="{disabled:disabledUpload}" class="upload-img" :on-change="loadJsonFromFile" :on-exceed="onExceed">
        <el-icon><Plus /></el-icon>  
        <template #file="{ file }">
              <!-- <span style="word-break: break-word; display: flex; align-items: center;padding: 10px;" v-if="file.name.endsWith('.pdf')">{{ file.name}}</span>
              <img v-else class="el-upload-list__item-thumbnail" :src="file.url" alt="" />333 -->
               <div v-if="file.url.endsWith('.zip')">
                  <img :src="zipUrl" class="img_css" />
                </div>
                <div v-else-if="file.url.endsWith('.pdf')">
                  <pdfViewer :url="file.url" class="img_css"></pdfViewer>
                </div>
                <div v-else-if="file.url.endsWith('.png') || file.url.endsWith('.jpg') || file.url.endsWith('.JPG') || file.url.endsWith('.jpeg')">
                  <img :src="file.url" class="img_css">
                </div>
              <div style="word-break: break-word; display: flex; align-items: center;padding: 10px;" v-else>{{ file.name}}</div>
              <span class="el-upload-list__item-actions">
                <span class="el-upload-list__item-preview" v-if="file.url.endsWith('.pdf') || file.url.endsWith('.png') || file.url.endsWith('.jpg') || file.url.endsWith('.JPG') || file.url.endsWith('.jpeg')" @click="handlePictureCardPreview(file)">
                  <el-icon><zoom-in /></el-icon>
                </span>      
                <span :disabled="loading" class="el-upload-list__item-delete" @click="downloadFile(file)">
                  <el-icon><Download /></el-icon>
                </span>
                  <span class="el-upload-list__item-preview" v-if="!disabledUpload" @click="handlePictureCardDelete(file)">
                  <el-icon><Delete /></el-icon>
                </span>
              </span>
          </template>
        </el-upload>
  </div>
  <el-dialog v-model="previewPic" v-if="previewPic" :with-header="false">
    <div v-if="dialogImageUrl.endsWith('.pdf')">
      <pdfViewer :url="dialogImageUrl"></pdfViewer>
    </div>
    <img w-full v-else :src="dialogImageUrl" alt="Preview Image" style="width: 100%;" />
  </el-dialog>
</template>
<script setup lang="ts">
import pdfViewer from '@/components/pdf'
import { computed, ref ,watch} from 'vue';
import { uploadFile } from '@/api/system/upload'
import zipUrl from '@/assets/images/Files.png'
import { downloadIamge, generateResume } from '@/utils/download'
import { ElMessage, UploadProps, type UploadFile, type UploadInstance } from 'element-plus'
const props = defineProps({
  detailFileList: {
    type: Array,
    default: () => {
      return []
    }
  },
   disabledUpload: {
    type: Boolean,
    default: false
  },
   maxLimit: {
    type: Number,
    default: 10
  },
})
const previewPic = ref(false);
const dialogImageUrl = ref('');
const handlePictureCardPreview = (file) => {
  previewPic.value = true;
  dialogImageUrl.value = file.url;
};
const handleDownload = (file) => {
  window.open(file.url,'_blank');
};
const handlePictureCardDelete=(file)=>{ //删除
  const index = fileList.value.findIndex(f => f.uid === file.uid); // 使用 uid 来找到文件并移除
    if (index !== -1) {
      fileList.value.splice(index, 1); // 移除文件项
    }
    emit('uploadSccess', fileList.value)
}
const beforeAvatarUpload = (rawFile: any) => {
  // console.log(rawFile)
  // let list = ['image/jpeg', 'image/jpg', 'image/png']
  // const isAccess = list.includes(rawFile.raw.type);
  const isLt3M = rawFile.size / 1024 / 1024 < 10;
  // if (!isAccess) {
  //   ElMessage.error('上传图片只能是 JPG/PNG 格式!');
  //   return false
  // }
  if (!isLt3M) {
    ElMessage.error('上传大小不能超过 10MB!');
    return false
  }
  return true
}
const uploadFiles = ref([])

const loadJsonFromFile = (file: any, fileList: never[]) => { //传参参考element-plus官网 （on-change）
  const result = beforeAvatarUpload(file)
  // 删除上传失败的文件
  if (!result) {
    fileList.splice(-1, 1);
  } else {
    uploadFiles.value = fileList  // 上传成功的 图片list
    submitUpload(file)
  }
}
const onExceed = (files: any, fileList: any) => {
  ElMessage.warning(`最多可上传${props.maxLimit}张,请先删除再上传`)  
}
const emit = defineEmits(['uploadSccess'])

//上传文件
const submitUpload = async (file: any) => { // 
  let formData = new FormData()
  console.log('file', file)
  formData.append('file', file?.raw)
  // let result = {}
  await uploadFile(formData).then((res: any) => {
    let result = res.data
    result.uid = file.uid
    result.status = 'success'
    let list= JSON.parse(JSON.stringify(fileList.value))
    list.push(result)
    emit('uploadSccess', list)
  }).catch((err: any) => {
    console.log('error:上传失败' + err)
    ElMessage.error('上传失败')
    return
  })
  // return result
}
const fileList=ref([])
const fileListMain = computed(() => {
  if (props.detailFileList) {
    fileList.value=[]
    // let detailFileList=JSON.parse(props.detailFileList) || []
    let detailFileList=props.detailFileList || []
    detailFileList.map((item: any) => {
      fileList.value.push(item)
    })
    return detailFileList
  } else {
    return []
  }

})
const loading=ref(false)
const downloadFile = (file: any) => {
  loading.value = true
  downloadIamge(file.url,file.originalFileName || new Date(Date.now()+28800000).toISOString()).then(res => {
    loading.value = false
  }).catch(err => {
    loading.value = false
  })
}
</script>
<style scoped>
.img_css {
  width: 100%;
  height: 100%;
  margin: 2px 2px 2px 2px;
  box-shadow: 0 0 15px #999;
  border-radius: 5px;
}

.icon_css_hover {
  background-color: #000000;
  opacity: 0.5;
}

#icon_css {
  margin-top: -65px;
  height: 65px;

}

#icon_css_View {
  width: 50px;
  cursor: pointer;
  font-size: 20px;
}

#icon_css_Download {
  width: 50px;
  cursor: pointer;
  font-size: 20px;
}
.disabled >>> .el-upload--picture-card{
  display: none;
}
</style>